#!/bin/sh
######################################################################
# file rc.common
# version 2.0.0
# date 2017-10-11
# author liumingyuan <liumingyuan@allwinnertech.com>
# base on openwrt
######################################################################
. $IPKG_INSTROOT/lib/functions.sh
. $IPKG_INSTROOT/lib/functions/service.sh

initscript=$1
action=${2:-help}
shift 2

start() {
    echo 'Not defined "start" functions!!!'
}

stop() {
    echo 'Not defined "stop" functions!!!'
}

restart() {
    trap '' TERM
	stop "$@"
	start "$@"
}

disable() {
    name="$(basename "${initscript}")"
    rm -f "$IPKG_INSTROOT"/etc/rc.d/S??$name
    rm -f "$IPKG_INSTROOT"/etc/rc.d/K??$name
}

enable() {
    name="$(basename "${initscript}")"
    disable
    [ -n "$START" -o -n "$STOP" ] || {
        echo "/etc/init.d/$name does not have a START or STOP value"
        return 1
    }
    [ "$START" ] && ln -s "../init.d/$name" "$IPKG_INSTROOT/etc/rc.d/S${START}${name##S[0-9][0-9]}"
    [ "$STOP"  ] && ln -s "../init.d/$name" "$IPKG_INSTROOT/etc/rc.d/K${STOP}${name##K[0-9][0-9]}"
}

list_contains() {
    local var="$1"
    local str="$2"
    local val

    eval "val=\" \${$var} \""
    [ "${val%% $str *}" != "$val" ]
}

# for procd
start_service() {
    echo 'Not defined "start_service" functions!!!'
}

stop_service() {
    echo 'Not defined "stop_service" functions!!!'
}

service_triggers() {
    echo 'Not defined "service_triggers" functions!!!'
}

service_running() {
    echo 'Not defined "service_running" functions!!!'
}

boot() {
    start "$@"
}

help() {
    cat <<EOF

	Available commands:
    start   Start the service
    stop    Stop the service
    restart Restart the service
EOF
}

procd_open_instance(){
	return 0
}

procd_close_instance(){
	return 0
}

procd_set_param(){
    local type="$1";shift
    case "$type" in
		env|data|limits|netdev|file|watch \
		|error|nice|oom_adj|user|seccomp|oom_score_adj \
		|capabilities|stdout|stderr|no_new_privs)
		;;
		respawn)
			 RESPAWN_FLAG=y
		;;
		command)
			if [ x${RESPAWN_FLAG} = "xy" ];then
				echo "$@" >> /tmp/processlog
				RESPAWN_FLAG=
			fi
			exec $@ >/dev/null
		;;
	 esac
}

. "$initscript"

[ -n "$USE_PROCD" ] && {
	start() {
		start_service "$@"
	}
	stop() {
		stop_service "$@"
	}
}

ALL_COMMANDS="start stop restart boot shutdown enable disable enabled"
list_contains ALL_COMMANDS "$action" || action=help
"$action" "$@" &
